package com.raising.modules.sys.controller;

import com.raising.framework.controller.BaseController;
import com.raising.framework.entity.ResultVo;
import com.raising.modules.sys.entity.User;
import com.raising.modules.sys.service.RoleService;
import com.raising.modules.sys.service.UserService;
import com.raising.utils.PasswordEntity;
import com.raising.utils.PasswordUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import com.raising.system.modules.framework.common.utils.DictUtils;

/**
 * 登录控制器
 * 
 * @author gaoy
 */
@Controller
@RequestMapping(value = "${adminPath}")
public class LoginController extends BaseController {

	@Autowired
	UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PasswordUtils passwordHelper;



	/**
	 * 登录
	 * @author gaoy
	 * 2017 2017-5-8 下午8:56:20
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = {RequestMethod.GET})
	public String login_get(HttpServletRequest request, Model model,String jumpUrl) {
		//登录后跳转路径
		model.addAttribute("jumpUrl",jumpUrl);
		return "signin";
	}


	/**
	 * 登录【现包含普通账号密码登录以及手机号快捷登录】
	 * @author gaoy
	 * 2017 2017-5-8 下午8:56:20
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = {RequestMethod.POST})
	public String login_post(HttpServletRequest request, HttpServletResponse response, Model model) {
		//ajax登录失败处理
		if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
			ResultVo resultVo = new ResultVo(ResultVo.FAILURE, "0", "登录失败", null);
			return renderString(response,resultVo);
		}

		//获取用户登录信息 验证已登录，跳转到管理页
//        String userName = UserUtils.getLoginUserName();
//        if(userName!=null){
//        	//判断是不是管理员，如果是管理员，则进入管理员后台
//			//登录之前的路径
//			String url = WebUtils.getSavedRequest(request).getRequestUrl();
//			return "redirect:" + url;
//
//
//        	//判断用户角色，不同角色跳转不同页面
//            //return "redirect:" + adminPath;
//			//默认页面展示路径
//			List<String> roleList = UserUtils.getLoginUser().getRoleIds();
//			String firstRole = roleList.get(0);
//			//根据角色查询默认首页路径
//			Role role = roleService.get(firstRole);
//			String siteUrl = role.getSiteUrl();
//			return "redirect:../" + siteUrl;
//        }
		String exceptionClassName = (String) request
				.getAttribute("shiroLoginFailure");
		model.addAttribute("username", request.getParameter("username"));
		String error = null;
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (IncorrectCredentialsException.class.getName().equals(
				exceptionClassName)) {
			error = "用户名/密码错误";
		}else if("randomCodeError".equals(exceptionClassName)){
		    error ="验证码错误";
		} else if (ExcessiveAttemptsException.class.getName().equals(
				exceptionClassName)) {
			error = "错误次数操作超过限制";
		} else if (LockedAccountException.class.getName().equals(
				exceptionClassName)) {
			error = "帐号被锁定";
		} else if (exceptionClassName != null) {
			error = "未知的错误";
		}
		model.addAttribute("msg", error);
		if (request.getParameter("forceLogout") != null) {
			error = "您已经被管理员强制退出，请重新登录";
			model.addAttribute("msg", error);
		}

//		String type = request.getParameter("type");

		return "signin";
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(){
		return "register2";
	}

	/**
	 * 用户注册
	 * @param username 用户名
	 * @param password 密码
	 * @param password 确认密码
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(String username,String password,String rpassword,Model model){
		String url = "register";
		//判断是否密码重复
		if(!password.equals(rpassword)){
			addMessage(model,"两次密码不一致");
		}else{
			User user = userService.getUserByUserName(username);
			if(user==null){
				user = new User();
				user.setUsername(username);
				user.setOrganizationId("1");
				user.setRoleIdsStr("3,");
				PasswordEntity passwordEntity = passwordHelper.encryptPassword(password);
				user.setSalt(passwordEntity.getSalt());
				user.setPassword(passwordEntity.getPassword());
				userService.save(user);
				addMessage(model,"注册成功");
				url = "login";
			}else{
				addMessage(model,"账号已存在");
			}
		}
		return url;
	}

}
